package com.westcom.vulb.activity;

import java.util.HashMap;
import java.util.List;
import com.westcom.vulb.bean.Card;
import com.westcom.vulb.bean.Card.ImageCardResource;
import com.westcom.vulb.bean.Card.TextCardResource;
import com.westcom.vulb.bean.Session;
import com.westcom.vulb.logic.CardDetail;
import com.westcom.vulb.logic.SessionManager;
import com.westcom.vulb.logic.card;
import com.westcom.vulb.protocal.http.Response;
import com.westcom.vulb.util.MyLog;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.View.OnClickListener;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.View;
import android.view.View.OnFocusChangeListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;

public class CardDetailFragment extends CardInfoBasicFragment {
    
    private LinearLayout mFuncBar;
    private ListView mListView;
    
    private ViewerAdapter mViewAdapter;
    
    private LayoutInflater mLayoutInflater;
    private boolean isEditMode = false;
    public static final int GET_IMG = 1010;
    private ImageView iv_func_bar_camera,iv_func_bar_abulm,iv_func_bar_smile;
    private int clickedItem = -1;
    public static final int REQUEST_IMAGE_DETAIL = 0x11;
    private Card mCardDetail = null;
    private SessionManager sm = null;
    private LoadCardDetailTask mLoader = null;
    private UpdateCardContentTask mUpdater = null;
    
    private OnClickListener l = new OnClickListener()
    {
		@Override
		public void onClick(View v) 
		{
			// TODO Auto-generated method stub
			switch(v.getId())
			{
				case R.id.iv_card_detail_item_resource_img:
				{
					int pos = (Integer)v.getTag();
					Card card = mCardDetail;
					ImageCardResource res = (ImageCardResource)card.resources.get(pos);
					int resId = res.getResId();
					Intent intent = new Intent();
	    	        intent.putExtra("resId",resId);    
	    	        intent.setClass(getActivity(), CardImageDetailActivity.class);
	    	        getActivity().startActivityForResult(intent, REQUEST_IMAGE_DETAIL);
				}break;
				case R.id.iv_card_detail_func_bar_camera:
				{}break;
				case R.id.iv_card_detail_func_bar_abulm:
				{}break;
				case R.id.iv_card_detail_func_bar_smile:
				{}break;
				default:{}break;
			}	
		}
    };
    private OnFocusChangeListener fl = new OnFocusChangeListener()
    {
		@Override
		public void onFocusChange(View v, boolean hasFocus) 
		{
			// TODO Auto-generated method stub
			switch(v.getId())
			{
				case R.id.et_card_detail_item_resource_text:
				{
					if(!hasFocus)
					{
						EditText et = (EditText)v;
						int pos = (Integer) et.getTag();
						String str = et.getText().toString();
						Card card = mCardDetail;
						TextCardResource res = (TextCardResource)card.resources.get(pos);
						if(str.isEmpty())
						{
							card.resources.remove(pos);					
						}else
						{
							res.setText(str);
						}
						mViewAdapter.notifyDataSetChanged();
					}
				}break;
				default:{}break;
			}
		}
	};
    
    private Handler mHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) 
        {
            switch(msg.what)
            {
	            case GET_IMG:
	            {
	            	if (msg.arg1 == Response.SUCCESS) 
	                {
	        			Session.getResourceResponse res = (Session.getResourceResponse)msg.obj;//success
	        			Bitmap bmp = BitmapFactory.decodeFile(res.filePath);
	        			ImageCardResource icr = mCardDetail.getImageRes(res.resId);
	        			if(icr != null) 
	        			{
	        				icr.mImage = bmp;
	        				if(icr.mView != null)
	        				{
	        					icr.mView.setImageBitmap(icr.mImage);
	        				}
	        			}
	                }
	            }break;
	            default:{}break;
            
            }
            return false;
        }
    });

    @Override
    public void onAttach(Activity activity) {
        // TODO Auto-generated method stub
        super.onAttach(activity);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        mLayoutInflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        sm = SessionManager.getInstance();
    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v,
            ContextMenuInfo menuInfo) {
        // TODO Auto-generated method stub
        super.onCreateContextMenu(menu, v, menuInfo);
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        // TODO Auto-generated method stub
        super.onCreateOptionsMenu(menu, inflater);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.card_detail, container, false);
        
        mFuncBar = (LinearLayout) v.findViewById(R.id.card_detail_func_bar);
        mListView = (ListView) v.findViewById(R.id.card_detail_content);
        mListView.setOnItemClickListener
        (
        	new OnItemClickListener()
        	{
        		@Override
        		public void onItemClick(AdapterView<?> arg0, View v, int pos,long id) 
        		{
        			Card card = mCardDetail;
        			if(card.resources.get(pos).mResType == Card.BasicCardResource.TYPE_IMAGE)
        			{
        				clickedItem = pos;
        				mViewAdapter.notifyDataSetChanged();
        			}
        		}
        	}
        );
        
        mViewAdapter = new ViewerAdapter();
        mListView.setAdapter(mViewAdapter);
        
        iv_func_bar_camera = (ImageView)v.findViewById(R.id.iv_card_detail_func_bar_camera);
        iv_func_bar_abulm = (ImageView)v.findViewById(R.id.iv_card_detail_func_bar_abulm);
        iv_func_bar_smile = (ImageView)v.findViewById(R.id.iv_card_detail_func_bar_smile);
        
        iv_func_bar_camera.setOnClickListener(l);
        iv_func_bar_abulm.setOnClickListener(l);
        iv_func_bar_smile.setOnClickListener(l);

        return v;
    }
    
    @Override
    public void onResume() 
    {
        super.onResume();
        if (mCardDetail == null) 
        {
        	loadComments(selfActivity().mCardId);
        } else 
        {
            mViewAdapter.setResoruces(mCardDetail.resources);
        }
    }

    @Override
    public void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
    }

    @Override
    public void onDestroyView() {
        // TODO Auto-generated method stub
        super.onDestroyView();
    }

    @Override
    public void onCardDetailLoaded() 
    {
    }
    
    private class ViewerAdapter extends BaseAdapter 
    {
        public static final int TAG_KEY_RESID    = 1;
        public static final int TAG_KEY_IMG      = 2;
        
        private List<Card.BasicCardResource> mData = null;
        
        private Bitmap mDefaultImg;
        
        @Override
        public int getCount() {
            return mData == null? 0:mData.size();
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View v = convertView;
            if (v == null) {
                v = mLayoutInflater.inflate(R.layout.card_detail_resource_item, null);
            }
            if (mDefaultImg == null) {
                mDefaultImg = BitmapFactory.decodeResource(getResources(), R.drawable.photo);
            }
            if(null == mData)
            {
            	return v;
            }
            if(clickedItem == position)
            {
            	v.setBackgroundColor(Color.rgb(00,127,127));
            }
            Card.BasicCardResource res = mData.get(position);
            EditText et = (EditText)v.findViewById(R.id.et_card_detail_item_resource_text);
            ImageView iv = (ImageView) v.findViewById(R.id.iv_card_detail_item_resource_img);
            et.setTag(position);
            iv.setTag(position);
            if (res.mResType == Card.BasicCardResource.TYPE_IMAGE) 
            {
            	Card.ImageCardResource ImageRes = (ImageCardResource)res;
            	ImageRes.mView = iv;
                et.setVisibility(View.GONE);
                iv.setVisibility(View.VISIBLE);
                Bitmap bmp = ImageRes.mImage;
                if (bmp == null) 
                {
                    iv.setImageBitmap(mDefaultImg);
                    Session s = SessionManager.getInstance().getCurrentSession();
                    s.getResource(ImageRes.getResId(), 0, mHandler.obtainMessage(GET_IMG));
                    MyLog.d("getResrouce:" + ImageRes.getResId());
                } else 
                {
                    iv.setImageBitmap(bmp);
                }
                iv.setOnClickListener(l);
            } else 
            {
            	Card.TextCardResource TextRes = (TextCardResource)res;
            	et.setVisibility(View.VISIBLE);
            	iv.setVisibility(View.GONE);

                et.setText(TextRes.getText());
                et.setEnabled(isEditMode);
                et.setOnFocusChangeListener(fl);
            }
            return v;
        }
        public void setResoruces(List<Card.BasicCardResource> resoruces) 
        {
            this.mData = resoruces;
            notifyDataSetChanged();
        }

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return null;
		}
    }
    public void SwitchMod()
    {
    	isEditMode = !isEditMode;
		if(isEditMode)
		{
			mFuncBar.setVisibility(View.VISIBLE);
		}else
		{
			mFuncBar.setVisibility(View.GONE);
		}
		mViewAdapter.notifyDataSetChanged();
    }
    
    protected void showdeleConfrimdialog(String title,final int userId) 
	{
		AlertDialog.Builder builder = new Builder(selfActivity());
		builder.setTitle(title);
		builder.setMessage(R.string.del_confirm);
		builder.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener()
		{
			@Override
			public void onClick(DialogInterface dialog, int which) 
			{
				// TODO Auto-generated method stub
				dialog.dismiss();
			}});
		
		builder.setNegativeButton(R.string.no, new DialogInterface.OnClickListener()
		{
			@Override
			public void onClick(DialogInterface dialog, int which) 
			{
				// TODO Auto-generated method stub
				dialog.dismiss();
			}});
		builder.create().show();
	}

    private class UpdateCardContentTask extends AsyncTask<String, Integer, String> {
        @Override
        protected String doInBackground(String... params) 
        {
        	String contents = mCardDetail.BuildHtml();
        	int []resourceIds = mCardDetail.getResIds();
        	card c = card.getInstanse();
        	Response res = c.StartEditCard(sm.getCurrSessionId(), mCardDetail.mCardId);
        	if(res.errno != Response.SUCCESS)
        	{
        		return res.errmsg;
        	}
        	res = c.UpdateCardContent(sm.getCurrSessionId(),mCardDetail.mCardId, contents, resourceIds);
        	if(res.errno != Response.SUCCESS)
        	{
        		return res.errmsg;
        	}
        	res = c.EndCardEdit(sm.getCurrSessionId(), mCardDetail.mCardId);
        	if(res.errno != Response.SUCCESS)
        	{
        		 return res.errmsg;
        	}else
        	{
        		return null;
        	}
        }
        @Override
        protected void onCancelled() 
        {
            super.onCancelled();
            if(mLoadingDialog.isShowing())
        	{
        		mLoadingDialog.hide();
        	}
            mUpdater = null;
        }
        @Override  
        protected void onPostExecute(String result) 
        {  
        	super.onPostExecute(result);
        	if(mLoadingDialog.isShowing())
        	{
        		mLoadingDialog.hide();
        	}
        	mUpdater = null;
        	if(result != null)
        	{
        		selfActivity().launchToast(result);
        		return;
        	}
        	
        }
	}
    
    private class LoadCardDetailTask extends AsyncTask<Integer, Integer, String> 
    {
        @Override
        protected String doInBackground(Integer... params) 
        {
            int cardId = params[0];
            card c = card.getInstanse();
            Response res = c.ReferenceCard(sm.getCurrSessionId(), cardId);
            if(res.errno != Response.SUCCESS)
            {
            	return res.errmsg;
            }
            Card card = null;
            if (res.data.get("contents") != null) 
            {
                card = Card.parse(cardId,(String) res.data.get("contents"));
                card.commentCount = Integer.valueOf((String) res.data.get("commentCount").toString());
                card.goodCount = Integer.valueOf((String) res.data.get("good").toString());
            } else 
            {
                return getResources().getString(R.string.card_parse_error);
            }
            mCardDetail = card;
            return null;
        }

        @Override
        protected void onCancelled() 
        {
            super.onCancelled();
            if(mLoadingDialog.isShowing())
        	{
        		mLoadingDialog.hide();
        	}
            mLoader = null;
        }

        @Override
        protected void onPostExecute(String result) 
        {
            super.onPostExecute(result);
            if(mLoadingDialog.isShowing())
        	{
        		mLoadingDialog.hide();
        	}
        	if(result != null)
        	{
        		selfActivity().launchToast(result);
        		return;
        	}
        	mLoader = null;
    		selfActivity().onDetailLoaded();
    		mViewAdapter.setResoruces(mCardDetail.resources);
        }
    }
    public void loadComments(int cardId) 
    {
        if (mLoader == null) 
        {
        	if(!mLoadingDialog.isShowing())
        	{
        		mLoadingDialog.show();
        	}
            mLoader = new LoadCardDetailTask();
            mLoader.execute(cardId);
        }
    }
    public void updateData()
    {
    	if (mUpdater == null) 
        {
    		if(!mLoadingDialog.isShowing())
        	{
        		mLoadingDialog.show();
        	}
    		mUpdater = new UpdateCardContentTask();
    		mUpdater.execute("");
        }
    }
    public Card getCardDetail()
    {
    	return this.mCardDetail;
    }
}